import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Tooltip,
  Rate,
  Checkbox,
  Tag,
  Popover,
  Spin,
  Empty,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Ellipsis from '@/components/Ellipsis';
import MyIcon from '@/components/MyIcon';
import IconButton from '@/components/IconButton';
import get from 'lodash/get';

import styles from './SearchResult.less';
import Link from 'umi/link';
import { stringify } from 'querystring';
import { SERVICE_STATUS } from '@/Constants';
import UpdateUserForm from '../UpdateUser/UpdateUser';
import router from 'umi/router';

const { Step } = Steps;
const { TextArea, Search } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;

@connect(({ base, product, org, loading }) => ({
  cargoTypes: base.cargoTypes,
  products: product.products,
  productGroups: product.productGroups,
  orgTree: org.orgTree,
  loading: loading.effects['user/queryUserListByKeywords'],
}))
@Form.create()
class SearchResult extends PureComponent {
  state = {
    userList: {
      list: [],
      pagination: {
        currentPage: 1,
        totalResult: 0,
      },
    },
    selectedRows: [],
    updateModalVisible: false,
    currentUser: {},
    roleList: null,
  };

  getColumns = () => [
    {
      title: '序号',
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
    },
    {
      title: '账号',
      dataIndex: 'userName',
      render: (text, record) => {
        return (
          <span>
            <a onClick={() => this.handleUpdateModalVisible(true, record)}>{text}</a>
            {record.isLocked ? <Icon style={{ marginLeft: 10 }} type="lock" /> : ''}
          </span>
        );
      },
    },
    {
      title: '姓名',
      dataIndex: 'fullName',
    },
    {
      title: '手机',
      dataIndex: 'mobilePhone',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      render: (text, record, index) => {
        return (
          <Ellipsis tooltip length={20} className={styles.ellipsis}>
            {text}
          </Ellipsis>
        );
      },
    },
    {
      title: '角色',
      render: (text, record) => {
        const { roleList } = this.state;
        return (
          <Popover
            content={
              <Spin spinning={!roleList}>
                <div style={{ minHeight: '20px', minWidth: '80px' }}>
                  {roleList &&
                    (roleList.length === 0 ? (
                      <Empty description="暂无角色" />
                    ) : (
                      roleList.map(role => {
                        return (
                          <p key={role.id} style={{ margin: '14px 20px' }}>
                            {role.name}({role.code})
                          </p>
                        );
                      })
                    ))}
                </div>
              </Spin>
            }
            trigger="click"
            placement="leftBottom"
          >
            <a
              onClick={e => {
                this.handleQueryRole(record.id);
              }}
            >
              查看
            </a>
          </Popover>
        );
      },
    },
  ];

  componentDidMount() {
    this.queryOrgTree();
    this.searchUsers();
  }

  queryOrgTree = () => {
    const { dispatch } = this.props;
    return dispatch({
      type: 'org/queryOrgTree',
    });
  };

  handleQueryRole = async id => {
    this.setState({
      roleList: null,
    });
    let res = await this.queryRoles(id);
    if (res.errorCode === 0) {
      this.setState({
        roleList: res.data || [],
      });
    }
  };

  queryRoles = id => {
    const { dispatch } = this.props;
    return dispatch({
      type: 'user/queryRoles',
      payload: {
        pathParams: {
          id,
        },
      },
    });
  };

  // 序号
  calcIndex = index => {
    const { userList } = this.state;
    let currentPage = get(userList, 'pagination.currentPage') || 1;
    let pageSize = get(userList, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };

  // 查找用户列表
  searchUsers = ({ pageIndex = 1, pageSize = 50, ...rest } = {}) => {
    const { dispatch, form } = this.props;
    form.validateFields(async (err, fieldsValue) => {
      let payload = {
        ...fieldsValue,
        pageIndex,
        pageSize,
        ...rest,
        q: this.props.location.query.q,
      };
      let res = await dispatch({
        type: 'user/queryUserListByKeywords',
        payload: {
          queryParams: payload,
        },
      });

      if (res.errorCode === 0) {
        this.setState({
          userList: {
            list: res.data,
            pagination: res.pagination,
          },
        });
      }
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.searchUsers(params);
    this.setState({
      selectedRows: [],
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleUpdateModalVisible = (flag, record = {}) => {
    this.setState({
      updateModalVisible: !!flag,
      currentUser: record,
    });
  };

  // 删除按钮
  handleDelete = () => {
    const { dispatch, location } = this.props;
    let ids = this.state.selectedRows.map(s => s.id);
    Modal.confirm({
      title: '删除账号',
      content: '确定删除已选账号？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'user/delete',
          payload: {
            data: ids,
          },
        }).then(res => {
          if (res.errorCode === 0) {
            message.success('删除成功');
            this.setState({
              selectedRows: [],
            });
            this.searchUsers();
          }
        });
      },
    });
  };

  // 锁定
  handleLock = () => {
    const { dispatch, location } = this.props;
    let ids = this.state.selectedRows.map(s => s.id);
    Modal.confirm({
      title: '锁定账号',
      content: '确定锁定已选账号？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'user/lock',
          payload: {
            data: ids,
          },
        }).then(res => {
          if (res.errorCode === 0) {
            message.success('锁定成功');
            this.setState({
              selectedRows: [],
            });
            this.searchUsers();
          }
        });
      },
    });
  };

  // 解锁
  handleUnLock = () => {
    const { dispatch, location } = this.props;
    let ids = this.state.selectedRows.map(s => s.id);
    Modal.confirm({
      title: '解锁账号',
      content: '确定解锁已选账号？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'user/unlock',
          payload: {
            data: ids,
          },
        }).then(res => {
          if (res.errorCode === 0) {
            message.success('解锁成功');
            this.setState({
              selectedRows: [],
            });
            this.searchUsers();
          }
        });
      },
    });
  };

  // 重置密码
  handleResetPwd = () => {
    const { dispatch, location } = this.props;
    let ids = this.state.selectedRows.map(s => s.id);
    Modal.confirm({
      title: '重置密码',
      content: '确定将已选账号重置密码？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return dispatch({
          type: 'user/resetPassword',
          payload: {
            data: ids,
          },
        }).then(res => {
          if (res.errorCode === 0) {
            message.success('重置成功');
            this.setState({
              selectedRows: [],
            });
          }
        });
      },
    });
  };

  // 编辑
  handleUpdate = fieldsValue => {
    const { dispatch, location } = this.props;
    const { currentUser } = this.state;
    dispatch({
      type: 'user/update',
      payload: {
        pathParams: {
          id: currentUser.id,
        },
        data: {
          ...currentUser,
          ...fieldsValue,
        },
      },
    }).then(res => {
      if (res.errorCode === 0) {
        message.success('更新成功');
        this.handleUpdateModalVisible();
        this.searchUsers();
      }
    });
  };

  canRemove = () => {
    const { selectedRows } = this.state;
    return !selectedRows.some(r => r.isMaster);
  };

  canLock = () => {
    const { selectedRows } = this.state;
    return !selectedRows.every(r => r.isLocked);
  };

  canUnLock = () => {
    const { selectedRows } = this.state;
    return selectedRows.every(r => r.isLocked);
  };

  renderHeader = () => {
    return (
      <div className={styles.goBack} onClick={() => router.go(-1)}>
        <Icon type="left" />
        <span style={{ paddingLeft: 10 }}>返回</span>
      </div>
    );
  };

  render() {
    const {
      form: { getFieldDecorator },
      cargoTypes,
      productGroups,
      loading,
      orgTree,
    } = this.props;

    const { updateModalVisible, currentUser, selectedRows, userList } = this.state;
    const updateProps = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
      currentUser,
      orgTree,
    };

    return (
      <PageHeaderWrapper className={styles.searchResult} title="返回" backRoute={'/system/user'}>
        <Card bordered={false}>
          <div>
            <div className={styles.tableListOperator}>
              {selectedRows.length > 0 && (
                <Fragment>
                  {this.canRemove() && (
                    <IconButton
                      title="删除"
                      icon="icon-delete"
                      onClick={() => this.handleDelete()}
                    />
                  )}
                  {this.canLock() && (
                    <IconButton
                      title="锁定"
                      icon="iconoss---suoding"
                      style={{ marginLeft: 10 }}
                      onClick={() => this.handleLock()}
                    />
                  )}
                  {this.canUnLock() && (
                    <IconButton
                      title="解锁"
                      icon="iconoss---jiesuo"
                      style={{ marginLeft: 10 }}
                      onClick={() => this.handleUnLock()}
                    />
                  )}
                  <IconButton
                    title="重置密码"
                    icon="iconoss---zhongzhi"
                    style={{ marginLeft: 10 }}
                    onClick={() => this.handleResetPwd()}
                  />
                </Fragment>
              )}
              <Button type="primary" disabled className={styles.disabledBtn}>
                添加
              </Button>
            </div>
            <StandardTable
              rowKey="id"
              showCheckbox
              selectedRows={selectedRows}
              loading={loading}
              data={userList}
              columns={this.getColumns()}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <UpdateUserForm {...updateProps} updateModalVisible={updateModalVisible} />
      </PageHeaderWrapper>
    );
  }
}

export default SearchResult;
